//
//  CustomRule.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/4/14.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import Foundation
import Eureka



/// 最大输入数量限制
public struct KPNumMaxRule: RuleType {

    let max: Int

    public var id: String?
    public var validationError: ValidationError

    public init(maxLength: Int, msg: String? = nil) {
        let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters"
        max = maxLength
        validationError = ValidationError(msg: ruleMsg)
    }

    public func isValid(value: String?) -> ValidationError? {
        guard let value = value else { return nil }
        guard value.count < max, value =~ RegexType.number else {
            return validationError
        }
        return nil
    }
}

public struct KPEmptyValueRule: RuleType {
    public var id: String?
    public var validationError: ValidationError

    public init(msg: String? = nil) {
        let ruleMsg = msg ?? "Field value"
        validationError = ValidationError(msg: ruleMsg)
    }

    public func isValid(value: String?) -> ValidationError? {
        guard let value = value else { return validationError }
        guard value.isEmpty else {
            return nil
        }
        return validationError
    }
}

extension RowType where Self : Eureka.BaseRow {



    /// 错误的 Label 样式
    func errorConfig() {
        onRowValidationChanged { (cell, row) in
            guard let rowIndex = row.indexPath?.row else {
                KPLog(row)
                KPLog(row.indexPath)
                return
            }
            while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
                row.section?.remove(at: rowIndex + 1)
            }
            if !row.isValid {
                for (index, validationMsg) in row.validationErrors.map({ $0.msg }).enumerated() {
                    let labelRow = LabelRow() {
                        $0.title = validationMsg
                        $0.cell.height = { 30 }
                    }.cellUpdate({ (cell, row) in
                        cell.contentView.backgroundColor = .red
                        cell.textLabel?.textColor = .white
                        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
                        cell.textLabel?.textAlignment = .right
                    })
                    row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
                }
            }
        }
    }


}


